from rest_framework.authtoken.views import ObtainAuthToken
from rest_framework.authtoken.models import Token
from rest_framework.response import Response

from rest_framework.views import APIView
# from django.contrib.auth.models import User  # django内置用户管理系统的Model
from user.models import UserInfo
from django.contrib.auth.hashers import make_password, check_password
from django.conf import settings
from user.models import UserLog
from rest_framework.authtoken.models import Token


#登录认证
class CustomAuthToken(ObtainAuthToken):

    def post(self, request, *args, **kwargs):
        try:
            username = request.data.get('username')
            user = UserInfo.objects.get(username=username)
            remote_ip = request.META.get('REMOTE_ADDR')
            serializer = self.get_serializer(data=request.data)
            if user.is_active == 1:
                if serializer.is_valid():
                    user = serializer.validated_data['user']
                    token, created = Token.objects.get_or_create(user=user)
                    res = {'code': 200,
                           'msg': '认证成功',
                           'token': token.key,
                           'username': user.username,
                           'role': user.role,
                           'first_name': user.first_name,
                           'avatar': user.avatar}
                else:
                    res = {'code': 500, 'msg': '用户名或密码错误！'}

                # 判断状态码是否等于200
                if res['code'] == 200:
                    msg = '登录成功'
                    status = 1
                else:
                    msg = '用户名或密码错误'
                    status = 2

                # 记录用户日志信息到日志表
                UserLog.objects.create(
                    username=username,
                    first_name=user.first_name,
                    remote_ip=remote_ip,
                    msg=msg,
                    status=status
                )
            else:
                res = {'code': 500, 'msg': '该账号被禁用，请联系管理员！'}
            return Response(res)
        except Exception as e:
            res = {'code': 500,'msg': '用户名或密码错误！'}
            return Response(res)



#修改密码
class ChangeUserPasswordView(APIView):
    def post(self, request):
        username = request.data.get('username')
        old_password = request.data.get('old_password')
        new_password = request.data.get('new_password')

        try:
            user = UserInfo.objects.get(username=username)
        except:
            res = {'code': 500, 'msg': '用户不存在！'}
            return Response(res)

        # 判断原密码对不对
        if check_password(old_password, user.password):
            user.password = make_password(new_password)  # 更新密码
            user.save()
            res = {'code': 200, 'msg': '修改密码成功！'}
        else:
            res = {'code': 500, 'msg': '原密码不正确！'}
        return Response(res)
    def put(self, request):
        username = request.data.get('username')
        new_password = request.data.get('new_password')

        try:
            user = UserInfo.objects.get(username=username)
        except:
            res = {'code': 500, 'msg': '用户不存在！'}
            return Response(res)

        user.password = make_password(new_password)  # 更新密码
        user.save()
        res = {'code': 200, 'msg': '密码设置成功！'}
        return Response(res)



#用户信息更新
class ChangeUserInfoView(APIView):
    def get(self,request):
        username = request.query_params.get('username')
        user_obj = UserInfo.objects.get(username=username)
        first_name = user_obj.first_name
        email = user_obj.email
        age = user_obj.age
        sex = user_obj.sex
        mobile = user_obj.mobile

        data = {'first_name': first_name, 'email': email, 'age': age, 'sex': sex, 'mobile': mobile}
        res = {'code': 200, 'data': data, 'msg': '获取成功'}
        return Response(res)

    def put(self,request):
        username = request.data.get('username')
        first_name = request.data.get('first_name')
        email = request.data.get('email')
        age = request.data.get('age')
        sex = request.data.get('sex')
        mobile = request.data.get('mobile')

        UserInfo.objects.filter(username=username).update(
            first_name=first_name,
            email=email,
            age=age,
            sex=sex,
            mobile=mobile
        )
        data = {'first_name': first_name}
        res = {'code': 200, 'data': data, 'msg': '更新成功'}
        return Response(res)
